3 追隨者

取得多個模型的資料

當處理一些複雜的資料時,您可能需要使用多個不同的模型來收集使用者輸入。例如,假設使用者登入資訊儲存在 user 資料表,而使用者個人資料資訊儲存在 profile 資料表,您可能會希望透過 User 模型和 Profile 模型來收集關於使用者的輸入資料。有了 Yii 模型和表單的支援,您可以解決這個問題,其方式與處理單一模型沒有太大差異。

在接下來的內容中,我們將展示如何建立一個表單,讓您可以收集 UserProfile 模型兩者的資料。

首先,用於收集使用者和個人資料的控制器操作可以寫成如下:

namespace app\controllers;

use Yii;
use yii\base\Model;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use app\models\User;
use app\models\Profile;

class UserController extends Controller
{
    public function actionUpdate($id)
    {
        $user = User::findOne($id);
        if (!$user) {
            throw new NotFoundHttpException("The user was not found.");
        }
        
        $profile = Profile::findOne($user->profile_id);
        
        if (!$profile) {
            throw new NotFoundHttpException("The user has no profile.");
        }
        
        $user->scenario = 'update';
        $profile->scenario = 'update';
        
        if ($user->load(Yii::$app->request->post()) && $profile->load(Yii::$app->request->post())) {
            $isValid = $user->validate();
            $isValid = $profile->validate() && $isValid;
            if ($isValid) {
                $user->save(false);
                $profile->save(false);
                return $this->redirect(['user/view', 'id' => $id]);
            }
        }
        
        return $this->render('update', [
            'user' => $user,
            'profile' => $profile,
        ]);
    }
}

update 操作中,我們首先從資料庫載入要更新的 $user$profile 模型。然後,我們呼叫 yii\base\Model::load() 以使用者輸入來填入這兩個模型。如果載入成功,我們將驗證這兩個模型,然後儲存它們——請注意,我們使用 save(false) 來跳過模型內部的驗證,因為使用者輸入資料已經過驗證。如果載入不成功,我們將呈現具有以下內容的 update 視圖

<?php
use yii\helpers\Html;
use yii\widgets\ActiveForm;

$form = ActiveForm::begin([
    'id' => 'user-update-form',
    'options' => ['class' => 'form-horizontal'],
]) ?>
    <?= $form->field($user, 'username') ?>

    ...other input fields...
    
    <?= $form->field($profile, 'website') ?>

    <?= Html::submitButton('Update', ['class' => 'btn btn-primary']) ?>
<?php ActiveForm::end() ?>

如您所見,在 update 視圖中,您將使用兩個模型 $user$profile 呈現輸入欄位。

發現錯字或您認為此頁面需要改進嗎?
在 github 上編輯 !